package com.ecoolex.discount.sales.core.manager;

import com.ecoolex.discount.sales.core.dao.DiscountOrderDetailDAO;
import com.ecoolex.discount.sales.entity.DiscountOrder;
import com.ecoolex.discount.sales.entity.DiscountOrderDetail;
import com.ecoolex.discount.sales.entity.DiscountOrderDetailExample;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.Date;
import java.util.List;

import static com.ecoolex.discount.sales.entity.DiscountOrderDetail.NOT_DELETED;

@Service
public class DiscountOrderDetailManager {
    @Autowired
    private DiscountOrderDetailDAO dao;

    @Autowired
    private CardVoucherPackageManager cardVoucherPackageManager;

    public void add(DiscountOrder order, DiscountOrderDetail detail, String createUser) {
        add(order, Lists.newArrayList(detail), createUser);
    }

    public void add(DiscountOrder order, List<DiscountOrderDetail> detailList, String createUser) {
        detailList.forEach(detail -> {
            detail.setOrderId(order.getOrderId());
            detail.setDeleted(NOT_DELETED);
            detail.setCreateUser(createUser);
            detail.setCreateTime(Date.from(Instant.now()));
            detail.setUpdateUser(createUser);
            detail.setUpdateTime(Date.from(Instant.now()));

        });
        dao.batchInsert(detailList);
        // 添加到卡券包
        cardVoucherPackageManager.add(order, detailList, createUser);
    }

    public List<DiscountOrderDetail> queryByOrderId(Integer orderId) {
        DiscountOrderDetailExample example = new DiscountOrderDetailExample();
        example.createCriteria()
                .andOrderIdEqualTo(orderId)
                .andDeletedEqualTo(NOT_DELETED);
        return dao.selectByExample(example);
    }
}